/**
 * 
 */
package com.hefei.blog.web.controller.desk.posts;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hefei.blog.base.data.Data;
import com.hefei.blog.base.upload.consts.FileConsts;
import com.hefei.blog.base.upload.image.UploadImageUtils;
import com.hefei.blog.base.utils.FileNameUtils;
import com.hefei.blog.base.utils.FilePathUtils;
import com.hefei.blog.base.utils.image.thread.ImageScaleExecutor;
import com.hefei.blog.base.utils.image.thread.ImageScaleThread;
import com.hefei.blog.web.controller.BaseController;
import com.hefei.frontend.framework.http.request.RequestThreadLocal;

@Controller
@RequestMapping("/post")
public class UploadController extends BaseController {
	
	private static Logger log = Logger.getLogger(UploadController.class);
	
	private static Map<String, String> errors = new HashMap<String, String>();
	
	static {
		errors.put("SUCCESS", "SUCCESS"); //默认成功
		errors.put("NOFILE", "未包含文件上传域");
		errors.put("TYPE", "不允许的文件格式");
		errors.put("SIZE", "文件大小超出限制");
		errors.put("REQUEST", "上传请求异常");
		errors.put("UNKNOWN", "未知错误");
	}
	
	@RequestMapping("/upload")
    public @ResponseBody Data upload(@RequestParam(value = "file", required=false) MultipartFile file,
    		Boolean scale, Integer size) {
    	Data data = Data.failure("error");
    	
    	if (file == null || file.isEmpty()) {
    		data = Data.failure(errors.get("NOFILE"));
			return data;
		}
    	
    	if (!FileNameUtils.checkImageFileType(file.getOriginalFilename())) {
    		data = Data.failure(errors.get("TYPE"));
			return data;
    	}
    	
    	try {
    		String relativePathAndName = UploadImageUtils.upload(file, FilePathUtils.getPicPath());
    		
//    		String path;
    		
			if (scale != null && scale == true) {
				ImageScaleExecutor.submit(new ImageScaleThread(FileConsts.ROOT_PIC + relativePathAndName, size+"_x"));
//				path = FileRepoFactory.getInstance().select().tempScale(file, FileConsts.tempDir, size);
			}
//			else {
//				path = FileRepoFactory.getInstance().select().temp(file, FileConsts.tempDir);
//			}
			data = Data.success("", relativePathAndName);
		} catch (Exception e) {
			log.error(RequestThreadLocal.getTimer() + " error", e);
			data = Data.failure(errors.get("UNKNOWN"));
		}
    	
    	return data;
    }
}
